#include "my_headerT2csC.h"

//V1.0

int recv2(int netfd,void *buf,int len){
    int total = 0;
    char *msg = (char *)buf;
    while(total<len){
        int now = recv(netfd,msg+total,len-total,0);
        total+=now;                                  
    }
    return total;
}


int recv_file(int netfd){
    train_t tnt;
    bzero(&tnt,sizeof(tnt));
    
    recv2(netfd,&tnt.msglen,sizeof(int));
    recv2(netfd,tnt.msg,tnt.msglen);
    off_t allsize = 0;
    off_t sum = 0;
    recv2(netfd,&allsize,sizeof(allsize));
    
    
    int opfd = open(tnt.msg,O_WRONLY|O_CREAT|O_TRUNC,0666);
    while(1){
        bzero(&tnt,sizeof(tnt));
        recv2(netfd,&tnt.msglen,sizeof(int));
        if(tnt.msglen == 0){
            printf("100.00%%\n");
            /* printf("C write %d B\n",tnt.msglen); */
            break;
        }
        sum +=tnt.msglen;
        printf("%5.2lf%%\r",100.0*sum/allsize);
        fflush(NULL);
        recv2(netfd,tnt.msg,tnt.msglen);
        write(opfd,tnt.msg,tnt.msglen);
        /* printf("C write %d B\n",tnt.msglen); */
    }
    close(opfd);
    return 0;
}
